package MtG.client.panels.dialogs;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * Connect.java is used for a dialog with the user to let the user tell which server to connect to.
 * @author Marek Sirp
 * @author Jaan Sepp
 *
 */
public class Connect extends JDialog{
	
	/**
	 * Determines if a de-serialized file is compatible with this class.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Label that holds the question that will be asked from the user.
	 */
	private JLabel askServer = new JLabel("Please enter server address");
	/**
	 * Field for holding the servers address.
	 */
	private String serverAddress = "";
	/**
	 * Field into which the user can write the server address.
	 */
	private JTextField addressField = new JTextField();
    /**
     * Making the panel for the dialog. 
     */
    private JPanel panel = new JPanel();
    /**
     * Making the "ok" button object.
     */
    private Button ok = new Button("Ok");
    /**
     * Making the "cancel" button object.
     */
    private Button cancel = new Button("Cancel");
	/**
	 * Making a box that displays its components from up do down. (in a column)
	 */
	private Box b = Box.createVerticalBox();

	/**
	 * @param parent frame on which this dialog will appear.
	 */
	public Connect(Frame parent){
		super(parent, "Connect to ...", true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	    getContentPane().add(b);
	    b.add(askServer);
	    b.add(addressField);
	    panel.add(ok);
	    ok.addActionListener(new Listener());
	    panel.add(cancel);
	    cancel.addActionListener(new Listener());	    
	    b.add(panel);
   	    pack();
	    setMinimumSize(getSize()); 
	    setMaximumSize(getSize());
	    //Placing the dialog box in the center of the parent frame.
	    setLocation((parent.getWidth()-getWidth())/2, (parent.getHeight()-getHeight())/2);
	    setVisible(true);
	}
	
    /**
     * This listener checks if the player has pressed the "ok" button and entered the server address.
     * If those conditions are met, the server address is read.
     * @author Marek Sirp
     * @author Jaan Sepp
     */
    public class Listener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent event) {
			if(event.getSource().equals(ok) && !addressField.getText().equals("")){
				serverAddress = addressField.getText();
				System.out.println(serverAddress);
				setVisible(false);
			} else {
				System.out.println("cancel");
				setVisible(false);
			}			
		}
    }
	
	/**
	 * Getter.
	 * @return user specified server address
	 */
	public String getAddress(){
		return serverAddress;
	}

}
